<?php

namespace app\api\controller\wdsxh;

use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\MemberVisitor;
use app\admin\model\wdsxh\Order;
use app\admin\model\wdsxh\UserBelong;
use app\admin\model\wdsxh\Member as Model;
use app\admin\model\wdsxh\MemberUnitLevel;
use app\admin\model\wdsxh\MemberUnit;
use app\admin\model\wdsxh\MemberUnitCat;
use app\admin\model\wdsxh\MemberProfile;
use think\Db;

/**
 * 会员接口
 */
class Member extends Base
{
    protected $noNeedLogin = ['lists','level','company','companycat','detail','payresult','visitor_lists','nativeplace','region'];
    protected $noNeedRight = ['*'];
    /*
     * 会员列表
     */
    public function lists()
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $level = $this->request->param('level', 0);
        $name = $this->request->param('name', null);
        $index = $this->request->param('index', 0);

        // 1=会长班子,2=地市商会会员,3=名誉会长,4=高级顾问
        $type = $this->request->param('type', 0);
        $cat = $this->request->param('cat', 0);
        // 籍贯(湖北)
        $nativeplace = $this->request->param('nativeplace',0);
        // 地区(浙江)
        $region = $this->request->param('region',0);
        // 所属商会
        $commerce_id = $this->request->param('commerce_id',0);

        $id = $this->request->param('id',0);

        $map = array(
            'status' => '1',
        );
        if (!empty($index)) {
            $map['index'] = $index;
        }
        if (!empty($level)) {
            $map['level_id'] = $level;
        }
        if (!empty($name)) {
            $map['name'] = ['like',"%{$name}%"];
        }

        $member_ids_arr = [];
        if (!empty($type)) {
            // 1=会长班子,2=地市商会会员,3=名誉会长,4=高级顾问
            switch ($type) {
                //会长班子
                case 1:
                    $map['level_id'] = ['in',[5,6,8,10,11,13,14]];
                    if (!empty($level)) {
                        $map['level_id'] = $level;
                        if($level == 10) {
                            $map['level_id'] = ['in',[10,14]];
                        }
                        if($level == 5) {
                            $map['level_id'] = ['in',[5,13]];
                        }
                    }
                    break;
                //地市商会会员
                case 2:
                    $map['level_id'] = ['in',[2,7,9]];
                    break;
                //名誉会长
                case 3:
                    $map['level_id'] = ['in',[1]];
                    break;
                //高级顾问
                case 4:
                    $map['level_id'] = ['in',[3]];
                    break;
            }
        }
        if (!empty($cat)) {
            $member_ids = model('app\admin\model\wdsxh\MemberUnit')->where(['cat_id' => $cat,'status' => 1])->column('id');
            if(!empty($member_ids)) {
                $member_ids_arr = array_merge($member_ids_arr,$member_ids);
            }
        }
        if(!empty($nativeplace)) {
            $data = model('app\common\model\Area')->get($nativeplace);
            $member_ids = Model::where(['birthplace' => ['like',"%{$data->shortname}%"]])->column('id');
            if(!empty($member_ids)) {
                $member_ids_arr = array_merge($member_ids_arr,$member_ids);
            }
        }
        if(!empty($region)) {
            $data = model('app\common\model\Area')->get($region);
            $member_ids = model('app\admin\model\wdsxh\MemberUnit')->where(['company_address' => ['like',"%{$data->shortname}%"]])->column('id');
            if(!empty($member_ids)) {
                $member_ids_arr = array_merge($member_ids_arr,$member_ids);
            }
        }
        if(!empty($commerce_id)) {
            $map['commerce_id'] = $commerce_id;
        }
        if(!empty($member_ids_arr)) {
            $map['id'] = ['in',$member_ids_arr];
        }
        if(!empty($id)) {
            $map['id'] = $id;
        }

        $total = Model::where($map)->count();
        $list = Model::where($map)
            ->with([
                'level',
                'company' => function($q) use($cat,$region){
                    $q->field('id,cat_id,member_id,company_name,company_address,company_address_detail,company_address_lat,company_address_lng');
                },
                'commerce' => function($q){
                    $q->field('id,title');
                },
            ])
            ->order('weigh','asc')
            ->field('id,name,picture,company_post,society_post,images,introduction,level_id,birthplace,commerce_id')
            ->page($page, $limit)
            ->select();
        if ($list) {
            foreach ($list as $row) {
                $row['picture'] = wdsxh_full_url($row['picture']);
                $row['images'] = wdsxh_full_url($row['images'], 1);
                if(empty($row->commerce)){
                    $row->commerce = [
                        'id' => 0,
                        'title' => '浙江省湖北商会',
                    ];
                }
            }
        }
        $data = array(
            'total' => $total,
            'list' => $list,
        );
        $this->success($data);
    }
    /*
     * 会员级别
     */
    public function level()
    {
        $list = MemberUnitLevel::where('status', 1)->order('weigh desc')->field('id,name')->select();
        $this->success($list);
    }

    /*
     * 会员单位
     */
    public function company()
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $level = $this->request->param('level', 0);
        $cat = $this->request->param('cat', 0);
        $name = $this->request->param('name', 0);
        // 籍贯(湖北)
        $nativeplace = $this->request->param('nativeplace',0);
        // 地区(浙江)
        $region = $this->request->param('region',0);

        $id = $this->request->param('id',0);

        $map = array(
            'status' => '1',
        );
        if (!empty($cat)) {
            $map['cat_id'] = $cat;
        }
        if (!empty($level)) {
            $map['level_id'] = $level;
        }
        if (!empty($name)) {
            $map['company_name'] = ['like',"%{$name}%"];
        }
        if(!empty($nativeplace)) {
            $data = model('app\common\model\Area')->get($nativeplace);
            $member_ids = Model::where(['birthplace' => ['like',"%{$data->shortname}%"]])->column('id');
            $map['member_id'] = ['in',$member_ids];
        }
        if(!empty($region)) {
            $data = model('app\common\model\Area')->get($region);
            $member_ids = model('app\admin\model\wdsxh\MemberUnit')->where(['company_address' => ['like',"%{$data->shortname}%"]])->column('id');
            if(array_key_exists('member_id',$map)) {
                $map['member_id'] = array_merge($map['member_id'],$member_ids);
            }else{
                $map['member_id'] = ['in',$member_ids];
            }
        }
        if (!empty($id)) {
            $map['id'] = $id;
        }
        $total = MemberUnit::where($map)->count();
        $list = MemberUnit::where($map)
            ->order('weigh desc')
            ->page($page, $limit)
            ->select();
        if ($list) {
            foreach ($list as $row) {
                $row['company_logo'] = wdsxh_full_url($row['company_logo']);
                $row['company_images'] = wdsxh_full_url($row['company_images'], 1);
                $row->cat;
                $row->level;
                $row->member;
                $row->label = $row->label ? array_filter(array_unique(array_values(json_decode($row->label, true)))) : array();
            }
        }
        $data = array(
            'total' => $total,
            'list' => $list,
        );
        $this->success($data);
    }
    /*
     * 行业分类
     */
    public function companycat()
    {
        $list = MemberUnitCat::where('status', 1)->order('weigh desc')->field('id,name,icon')->select();
        if ($list) {
            foreach ($list as $row) {
                $row['icon'] = wdsxh_full_url($row['icon']);
            }
        }
        $this->success($list);
    }

    /*
     * 籍贯(湖北)
     */
    public function nativeplace()
    {
        $data = model('app\common\model\Area')->field('id,shortname,name')->where(['pid' => 1709])->select();
        $this->success('请求成功', $data,200);
    }

    /*
     * 地区(浙江)
     */
    public function region()
    {
        $data = model('app\common\model\Area')->field('id,shortname,name')->where(['pid' => 933])->select();
        $this->success('请求成功', $data,200);
    }

    /*
     * 加入商会
     */
    public function add()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $params = $this->request->param();
        $params['uid'] = $this->auth->id;
        $params['status'] = '0';
        $params['createtime'] = time();
        if (empty($params['name'])) {
            $this->error('姓名不能为空');
        }
        if (empty($params['origo'])) {
            $this->error('籍贯不能为空');
        }
        if (empty($params['ethnic'])) {
            $this->error('民族不能为空');
        }
        if (empty($params['mobile'])) {
            $this->error('联系电话不能为空');
        }
        MemberProfile::create($params, true);
        $this->success('提交成功！');
    }

    /*
     * 会员详情
     */
    public function detail()
    {
        $id = $this->request->param('id');
        $type = $this->request->param('type', 1);
        if (empty($id)) {
            $this->error('id参数错误');
        }

        if ($type == 1) {
            $data = Model::where('id', $id)->field('id,name,picture,mobile,company_post,society_post,images,introduction,level_id,birthplace,jointime,expiretime')->find();
            if (!$data) {
                $this->error('会员信息不存在');
            }
            $data->level;
            $data->company;
            $data['picture'] = wdsxh_full_url($data['picture']);
            $data['images'] = wdsxh_full_url($data['images'], 1);
            if ($data->company) {
                $data->company->cat;
                $data->company->level;
                $data->company->company_logo = wdsxh_full_url($data->company->company_logo);
                $data->company->company_images = wdsxh_full_url($data->company->company_images, 1);
                $data->company->label = $data->company->label ? array_filter(array_unique(array_values(json_decode($data->company->label, true)))) : array();
            }
        } else {
            $data = MemberUnit::where('id', $id)->find();
            if (!$data) {
                $this->error('您还不是会员，请先申请入会');
            }
            $member = Model::get($data->member_id);
            if (!$member) {
                $this->error('您还不是会员');
            }
            $data['company_logo'] = wdsxh_full_url($data['company_logo']);
            $data['company_images'] = wdsxh_full_url($data['company_images'], 1);
            $data->cat;
            $data->level;
            $data->member;
            if ($data->member) {
                $data->member->picture = $data->member->picture ? wdsxh_full_url($data->member->picture) : '';
                $data->member->level_id = (new MemberUnitLevel())->where('id', $data->member->level_id)->value('name');
            }
            $data->label = $data->label ? array_filter(array_unique(array_values(json_decode($data->label, true)))) : array();
        }
        $user_id = $this->auth->id;
        if ($user_id) {
            $memberVisitorObj = MemberVisitor::where('uid', $user_id)->where('member_id', $id)->find();
            if ($memberVisitorObj) {
                $memberVisitorObj->createtime = time();
                $memberVisitorObj->save();
            } else {
                $visitor_data = array(
                    'uid' => $user_id,
                    'member_id' => $id,
                    'createtime' => time(),
                );
                MemberVisitor::create($visitor_data);
            }
        }

        $this->success($data);
    }

    /*
     * 访客列表
     */
    public function visitor_lists()
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $member_id = $this->request->param('id', 0);
        $map = array(
        );
        if (!empty($member_id)) {
            $map['member_id'] = $member_id;
        }
        $total = MemberVisitor::where($map)->count();
        $list = MemberVisitor::where($map)
            ->alias('visitor')
            ->order('visitor.createtime desc')
            ->join('user user', 'user.id = visitor.uid')
            ->field('user.avatar')
            ->page($page, $limit)
            ->select();
        foreach ($list as $v){
            $v['avatar'] = wdsxh_full_url($v['avatar']);
        }
        $data = array(
            'total' => $total,
            'list' => $list,
        );
        $this->success($data);
    }

    /*
     * 缴纳明细
     */
    public function member_pay_lists()
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $map = array(
            'type' => 2,
            'uid' => $this->auth->id,
            'status' => '2',
        );
        $total = Order::where($map)->count();
        $list = Order::where($map)
            ->order('createtime desc')
            ->field('money,createtime')
            ->page($page, $limit)
            ->select();
        if ($list) {
            foreach ($list as $row) {
                $row->createtime = date('Y-m-d H:i:s', $row->createtime);
            }
        }

        $data = array(
            'total' => $total,
            'list' => $list,
        );
        $this->success($data);
    }
    /*
     * 会费缴纳详情
     */
    public function memberShipPayDetail()
    {
        $data = Model::where('uid', $this->auth->id)->field('id,name,picture,mobile,level_id,jointime,expiretime,status')->find();
        if (!$data) {
            $apply = MemberProfile::where('uid', $this->auth->id)->find();
            if (!$apply) {
                $this->error('入会信息不存在');
            }
            if ($apply['status'] == '0') {
                $this->error('入会信息待管理员审核通过');
            } elseif ($apply['status'] == '2') {
                $this->error('入会信息被驳回，请重新提交审核');
            } else {
                $this->error('发生未知错误，请联系系统管理员');
            }
        }
        $data['level'] = (new MemberUnitLevel())->get($data['level_id']);
        $data->picture = wdsxh_full_url($data->picture);
        if ($data['status'] == '-1') {
            $data['jointime'] = $data['level']['jointime'];
            $data['expiretime'] = $data['level']['expiretime'];
        }
        $data->hidden(['level_id','status']);
        $this->success($data);
    }

    /*
     * 会费缴纳
     */
    public function memberShipPay()
    {
        $user = \app\admin\model\User::get($this->auth->id);
        if (!$user || $user['status'] != 'normal') {
            $this->error('用户信息不存在或已被拉黑');
        }
        $member = Model::where('uid', $user->id)->find();
        if (!$member) {
            $this->error('会员信息不存在或会员状态错误');
        }
        $level = $member->level;
        $orderData = array(
            'uid' => $this->auth->id,
            'items_id' => $member->id,
            'type' => 2,
            'order_sn' => wdsxh_create_order(),
            'money' => $level->expense,
            'status' => floatval($level->expense) == 0 ? '2' : '1',
            'createtime' => time()
        );
        $res = Order::create($orderData);
        if (floatval($level->expense) > 0 && $res) {
            try {
                $openid = (new UserBelong())->where('user_id',$user['id'])->value('openid');
                $conf = Wxapp::unify('会费缴纳', $res->order_sn, $res->money, $openid, request()->domain() . '/api/wdsxh/member/payresult');
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('success', $conf, 2);
        } else {
            $res->paytime = time();
            $res->remark = '无需支付';
            $res->save();
            $member->expiretime = date('Y-m-d', strtotime("+{$level->deadline} year", strtotime($member->expiretime)));
            $member->save();
            //入会申请成功通知
            $Coceral = wdsxh_get_coceral();
            try {
                $conf = $this->configObj;
                $data = [
                    'thing3' => [
                        'value' => mb_substr($Coceral['name'], 0, 20)
                    ],
                    'time2' => [
                        'value' => date('Y-m-d H:i:s'),
                    ],
                    'thing1' => [
                        'value' => mb_substr('恭喜您已成功加入' . $Coceral['name'], 0, 20),
                    ]
                ];
                Wxapp::subscribeMessage($conf['initiation_success'], trim(wdsxh_get_openid($this->auth->id)), '/pages/Personal/index', $data);
            } catch (\think\Exception $e) {
            }

            $this->success('会费缴纳成功');
        }
    }
    /*
     * 会费缴纳支付处理
     */
    public function payresult()
    {
        $pay = Wxapp::getPay();
        $response = $pay->handlePaidNotify(function ($message, $fail) {

            $order = Order::where('order_sn', $message['out_trade_no'])->find();
            if (!$order || $order->status == '2') {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $order->paytime = time();
                    $order->status = '2';
                    $member = Model::where('id', $order->items_id)->find();
                    $memberUnitLevelObj = (new \app\admin\model\wdsxh\MemberUnitLevel())->get($member['level_id']);
                    $member->jointime = $memberUnitLevelObj['jointime'];
                    $member->expiretime = $memberUnitLevelObj['expiretime'];
                    if ($member->status == '-1') {
                        $member->status = '1';
                    }
                    $member->save();
                    $fill_company = 0;
                    $memberProfileModel = new MemberProfile();
                    $memberProfileObj = $memberProfileModel->where('uid', $order['uid'])->value('content');
                    $content_array = json_decode($memberProfileObj, true);
                    foreach ($content_array as $k => $v) {
                        if ($v['field'] == 'company') {
                            $fill_company = 1;
                            $company_name = $v['value'];
                        }
                    }
                    if ($fill_company) {
                        $member_unit_data = array(
                            'level_id' => $member->level_id,
                            'member_id' => $member->id,
                            'company_name' => $company_name,
                            'status' => '0',
                            'createtime' => time(),

                        );
                        \app\admin\model\wdsxh\MemberUnit::create($member_unit_data);
                    }
                    //入会申请成功通知
                    $Coceral = wdsxh_get_coceral();
                    try {
                        $conf = $this->configObj;
                        $data = [
                            'thing3' => [
                                'value' => mb_substr($Coceral['name'], 0, 20)
                            ],
                            'time2' => [
                                'value' => date('Y-m-d H:i:s'),
                            ],
                            'thing1' => [
                                'value' => mb_substr('恭喜您已成功加入' . $Coceral['name'], 0, 20),
                            ]
                        ];
                        Wxapp::subscribeMessage($conf['initiation_success'], trim(wdsxh_get_openid($member->uid)), '/pages/Personal/index', $data);
                    } catch (\think\Exception $e) {
                        $this->error($e->getMessage());
                    }
                } elseif ($message['result_code'] === 'FAIL') {
                    $order->status = '3';
                }
            } else {
                return $fail('FAIL');
            }
            $order->save();
            return true;
        });
        $response->send();
    }

    //是否是管理员
    public function is_admin()
    {
        $id = $this->auth->id;
        if (!$id) {
            $this->error('用户不存在');
        }
        $set_admin = UserBelong::where('user_id', $id)->value('set_admin');
        $this->success('请求成功', ['set_admin' => $set_admin]);
    }

    //管理员提交订阅
    public function submit_subscribe()
    {
        $count = 0;
        $id = $this->auth->id;
        $subscribeObj = Db::name('wdsxh_member_subscribe')->where('user_id', $id)->where('type', 1)->find();
        if ($subscribeObj) {
            $count = Db::name('wdsxh_member_subscribe')->where('user_id', $id)->where('type', 1)->setInc('count');
        } else {
            $data = ['user_id' => $id, 'count' => 1,'type' => 1];
            $count = Db::name('wdsxh_member_subscribe')->insert($data);
        }
        if ($count) {
            $this->success('订阅成功');
        } else {
            $this->error('订阅失败');
        }
    }

    //管理员订阅数量
    public function subscribe_count()
    {
        $id = $this->auth->id;
        $subscribeObj = Db::name('wdsxh_member_subscribe')->where('user_id', $id)->where('type', 1)->find();
        if ($subscribeObj) {
            $this->success('查询成功', ['subscribe_count' => $subscribeObj['count']]);
        } else {
            $this->success('查询成功', ['subscribe_count' => 0]);
        }
    }

    //todo 原user控制器方法放这里
    public function member()
    {
        $member = \app\admin\model\wdsxh\Member::where('uid', $this->auth->id)->order('id desc')->find();
        if ($this->request->isPost() && $member) {
            $params = $this->request->param();
            $member['name'] = $params['name'];
            $member->mobile = $params['mobile'];
            $member->picture = $params['picture'];
            $member->company_post = $params['company_post'];
            $member->society_post = $params['society_post'];
            $member->images = $params['images'];
            $member->introduction = $_POST['introduction'];
            $member->birthplace = $params['birthplace'];
            $member->save();
            $this->success('修改成功！');
        }
        if ($member) {
            $member->level;
            $member = $member->toArray();
        } else {
            $this->error('非会员用户无法访问');
        }
        $this->assign('member', $member);
        return $this->view->fetch();
    }

    //todo 原user控制器方法放这里
    public function unit()
    {
        $member = \app\admin\model\wdsxh\Member::where('uid', $this->auth->id)->order('id desc')->find();
        if (!$member) {
            $this->error('非会员用户无法访问');
        }
        $unit = \app\admin\model\wdsxh\MemberUnit::where('member_id', $member['id'])->order('id desc')->find();
        if (!$unit) {
            $this->error('单位信息不存在');
        }
        if ($this->request->isPost() && $member && $unit) {
            $params = $this->request->param();
            $params['label'] = empty($_POST['label_data']) ? '' : $_POST['label_data'];
            $params['status'] = '1';
            $params['company_introduce'] = $_POST['company_introduce'];
            $unit->allowField(true)->save($params);
            $this->success('修改成功！');
        }
        $this->assign('member', $unit);
        return $this->view->fetch();
    }

    //是否是会员
    public function is_member(){
        $memberObj = Model::where('uid',$this->auth->id)->where('status','1')->find();
        if($memberObj && (strtotime($memberObj['expiretime']) > time())) {
            $status = 1;
        } else {
            $status = 0;
        }
        $this->success('请求成功！',['status'=>$status]);
    }


    /**
     * @ApiTitle    (修改会员和企业信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/wdsxh/member/editMemberAndUnitInfo)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="name", type="string", required=true, description="会员姓名")
     * @ApiParams   (name="mobile", type="string", required=true, description="联系电话")
     * @ApiParams   (name="birthplace", type="string", required=true, description="会员籍贯")
     * @ApiParams   (name="picture", type="string", required=false, description="会员照片")
     * @ApiParams   (name="level_id", type="string", required=false, description="商会职务")
     * @ApiParams   (name="company_post", type="string", required=false, description="公司职务")
     * @ApiParams   (name="society_post", type="string", required=false, description="社会职务")
     * @ApiParams   (name="introduction", type="string", required=false, description="会员简介")
     * @ApiParams   (name="cat_id", type="string", required=true, description="行业分类")
     * @ApiParams   (name="company_name", type="string", required=true, description="公司名称")
     * @ApiParams   (name="company_logo", type="string", required=false, description="公司LOGO")
     * @ApiParams   (name="company_introduce", type="string", required=true, description="公司介绍")
     * @ApiParams   (name="company_product", type="string", required=true, description="公司产品")
     * @ApiParams   (name="company_mobile", type="string", required=false, description="公司电话")
     * @ApiParams   (name="company_address", type="string", required=true, description="公司地址")
     * @ApiParams   (name="company_address_detail", type="string", required=true, description="公司详细地址")
     * @ApiParams   (name="company_address_lng", type="string", required=true, description="公司地址经纬度")
     * @ApiParams   (name="company_address_lat", type="string", required=true, description="公司地址经纬度")
     * @ApiParams   (name="company_site", type="string", required=false, description="公司网址")
     * @ApiParams   (name="company_email", type="string", required=false, description="公司邮箱")
     * @ApiReturn   ({
        'code':'200',
        'msg':'请求成功'
     })
    */
    public function editMemberAndUnitInfo(\app\common\model\MemberModel $MemberModel, \app\api\validate\MemberValidate $MemberValidate)
    {
        $this->request->filter('');
        if(!$this->request->isPost()){
            $this->success('请求方式错误',[],40001);
        }
        $params = $this->request->post();
        if(!$MemberValidate->check($params,[],'editMemberAndUnitInfo')){
            $this->success($MemberValidate->getError(),$params,40001);
        }
        $user_id = $this->auth->id;
        $data = $MemberModel->editMemberAndUnitInfo($params,$user_id);
        $this->success($data['msg'], $data['data'], $data['code']);
    }

}
